// import "@css/bootstrap.min.css"
import "bootstrap/dist/css/bootstrap.css"
import "bootstrap/dist/js/bootstrap.js"
import "@scss/header.scss"
import "@scss/motaikuang.scss";
import "@scss/examinationProcess.scss"
import "@scss/inTheExam.scss"
import $ from "jquery"
import http from "../utils/request.js";
import { renderTestQuestions,renderName} from "./render.js";



// 试题渲染
(function () {
    renderName();
    let dateStart = new Date();
    let dateCurrent = new Date();
    let timeStart = dateStart.getTime();
    sessionStorage.setItem("timeStart", timeStart);
    let timeEnd = timeStart + 1000 * 60 * 5;
    sessionStorage.setItem("timeEnd", timeEnd);
    console.log(timeStart, timeEnd);
    renderTestQuestions();
})();


//考试时间判断
function timer() {
    let dateCurrent = new Date();
    let currentTime = dateCurrent.getTime();
    let timeEnd = sessionStorage.getItem("timeEnd");
    let times = (timeEnd - currentTime) / 1000;
    // console.log(currentTime);
    let fen = parseInt(times / 60);
    let miao = parseInt(times % 60);
    $("#timer").html(`0${fen}:${miao}`);
    if (times == 60) {
        alert("剩余时间不足一分钟，请把控时间！")
    }else if(times<=0){
        clearInterval(timerSet);
    }
}

let timerSet = setInterval(timer, 1000);

//选题号按钮
//判断是否选中

$('body').on('click', '#anwer-btns', function (e) {
    const buttons = $(this).children();
    for (let i = 0; i < buttons.length; i++) {
        if ($(buttons[i]).attr('data-flag')) {
            $(buttons[i]).attr('class', 'greenBack');
        } else {
            $(buttons[i]).attr('class', '');
        }
    }
    const $this = $(e.target);
    //获取对应按钮的题目class
    const $thisShowQusetionClass = $this.attr("id").split('-')[0];
    //对应题目显示
    $('.carousel-item').hide();
    $(`.${$thisShowQusetionClass}`).show();
    $(`.${$thisShowQusetionClass}`).addClass('active').siblings("div").removeClass('active');

    //如果按钮未选中状态
    if ($this.attr('class') == '') {
        //点击变成答题状态
        $this.addClass('inTheAns');

    } else if ($this.attr('class').indexOf('greenBack') != -1) {
        $this.addClass('inTheAns').removeClass('greenBack');
    }

})


//选项选择
$('body').on('click', '.options dd', async function () {

    $(this).addClass('activeBlue').siblings().removeClass('activeBlue');
    let _id = $(this).parents("div").attr('class').split(' ')[1];
    $(`#${_id}-btn`).attr('data-flag', true);

    let tests_id = sessionStorage.getItem("testId");
    let user_id = localStorage.getItem("userId");
    let { questions } = await http({ url: "/api/beginExam/getExamUser", type: "post", data: { tests_id, user_id } });

    let quesArr = JSON.parse(sessionStorage.getItem("quesArr"));

    let selectVal = $(this).find("span:first-child").html();
    let status = false;
    if (quesArr == null) {
        quesArr = [];
        quesArr[quesArr.length] = { _id, selectVal };
        $(".answer-card .corR").html(`未答${questions.length - quesArr.length}题`);
    } else {

        for (let i = 0; i < quesArr.length; i++) {
            if (quesArr[i]._id == _id) {
                status = true;
                quesArr[i].selectVal = selectVal;
                break;
            }
        }
        if (!status) {
            quesArr[quesArr.length] = { _id, selectVal };
            $(".answer-card .corR").html(`未答${questions.length - quesArr.length}题`);
        }

    }

    sessionStorage.setItem("quesArr", JSON.stringify(quesArr));
});

//点击下一题
$('body').on('click', '.testBtn', function () {
    if ($($(this).parents()[1]).next().length > 0) {
        $('.carousel-item').hide();
        $($(this).parents()[1]).next().show();
        const selectBtnClass = $($(this).parents()[1]).next().attr('class').split(' ')[1];
        if ($(`#${selectBtnClass}-btn`).prev().attr('data-flag')) {
            $(`#${selectBtnClass}-btn`).attr('class', 'inTheAns').prev().attr('class', 'greenBack');
        } else {
            $(`#${selectBtnClass}-btn`).attr('class', 'inTheAns').prev().attr('class', '');
        }
    } else if ($($(this).parents()[1]).next().length == 0) {
        alert('最后一题');
    }

});
//模态框渲染
$('body').on('click', '.dati .hand-paper', async function () {

    let tests_id = sessionStorage.getItem("testId");
    let user_id = localStorage.getItem("userId");

    let { questions } = await http({ url: "/api/beginExam/getExamUser", type: "post", data: { tests_id, user_id } });

    let quesArr = JSON.parse(sessionStorage.getItem("quesArr"));

    $("#allQues").html(questions.length);
    $("#finishQues").html(quesArr.length);
    $("#unfinishQues").html(questions.length - quesArr.length);
});


$('body').on('click', '#submitTest', async function () {
    let test_id = sessionStorage.getItem("testId");
    let user_id = localStorage.getItem("userId");

    let quesArr = JSON.parse(sessionStorage.getItem("quesArr"));

    let { totleScore, allScore } = await http({ url: "/api/beginExam/getTotleScore", type: "post", data: { quesArr: JSON.stringify(quesArr) } });
    sessionStorage.setItem("totleScore", totleScore);
    sessionStorage.setItem("allScore", allScore);

    await http({ url: "/api/beginExam/addcompletedTest", type: "post", data: { userAnswerArr: JSON.stringify(quesArr), score: totleScore, test_id, user_id } });

    await http({ url: "/api/beginExam/addErrorTest", type: "post", data: { userAnswerArr: JSON.stringify(quesArr), user_id } });

    window.location.href = "../examResult.html";

});


